#!/usr/bin/env python3

"""
Module for performing all tasks in specdb
"""

import os
import pandas as pd
import sqlite3
import sys

from specdb.Insert import find_uniq_constraint

def summary(db=None, table=None):
	"""
	Display contents of a SpecDB table
	
	Parameters
	----------
	+ db		path to a specdb database file
	+ table		str, name of table to display contents of
	
	Returns
	-------
	print to stdout dataframe of SpecDB table contents, order alphabetically
	"""
	
	if db is None:
		print("Must provide a database file")
		print("Aborting")
		sys.exit()
	
	if table is None:
		print("Must provide a table to summarize")
		print("Aborting")
		sys.exit()
	
	pd.set_option('display.max_columns', None)
	pd.set_option('max_colwidth', 20)
	pd.set_option('display.max_rows', None)
	pd.set_option('display.width', 110)
	pd.set_option('max_rows', None)
	
	# connect to database
	conn = sqlite3.connect(os.path.abspath(db))
	conn.row_factory = sqlite3.Row
	c = conn.cursor()
	
	# collect the columns that define unique constraint for the table
	if table == 'summary':
		sql = f"SELECT * FROM {table}"
	else:
		uniq_cols = find_uniq_constraint(table=table, cursor=c)
		
		# perform sql select * query from provided table
		if len(uniq_cols) == 1:
			sql = f"SELECT * FROM {table} ORDER BY {uniq_cols[0]} ASC"
		elif len(uniq_cols) == 2:
			sql = f"SELECT * FROM {table} ORDER BY {uniq_cols[0]} ASC,"
			sql += f" {uniq_cols[1]} ASC"
		else:
			sql = f"SELECT * from {table}"
	
	df = pd.read_sql(sql, conn)
	blankindex = [''] * len(df)
	df.index = blankindex
	df = df.rename(columns=lambda x: x[:14])
	
	print()
	print(df)
	print()
	
	return